package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentService;
import com.heima.comment.vos.ApCommentVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;
    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //检查参数
        if (dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent()!=null&&dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"评论内容不能超过140个字");
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"请登录后再评论");
        }
        //安全过滤 TODO

        //保存评论
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"登录信息有误");
        }
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setImage(apUser.getImage());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.insert(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        int size = 10;

        //2.查询当前文章对应的评论

        List<ApComment> apComments = null;

        //是首页
        if (dto.getIndex() == 1) {
            //查询热点评论  5
            Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC, "likes"));
            apComments = mongoTemplate.find(query, ApComment.class);
            //查询普通评论
            if (apComments != null && apComments.size() > 0) {
                size = size - apComments.size();
                //是首页
                Query query1 = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("flag").is(0).and("createdTime").lt(dto.getMinDate())).limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
                List<ApComment> apComments1 = mongoTemplate.find(query1, ApComment.class);
                apComments.addAll(apComments1);
            } else {

                Query query2 = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("flag").is(0).and("createdTime").lt(dto.getMinDate())).limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
                apComments = mongoTemplate.find(query2, ApComment.class);
            }

        } else {
            //不是首页
            Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("flag").is(0).and("createdTime").lt(dto.getMinDate())).limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
            apComments = mongoTemplate.find(query, ApComment.class);

        }

        List<ApCommentVo> list = new ArrayList<>();

        //3.没有登录 直接返回数据
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apComments);
        } else {
            //4.已登录，需要判断当前用户点赞了哪些评论
            List<String> idList = apComments.stream().map(x -> x.getId()).collect(Collectors.toList());
            List<ApCommentLike> apCommentLikes = mongoTemplate.find(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").in(idList)), ApCommentLike.class);
            if (apComments != null && apCommentLikes != null) {
                apComments.forEach(comment -> {
                    ApCommentVo apCommentVo = new ApCommentVo();
                    BeanUtils.copyProperties(comment, apCommentVo);
                    for (ApCommentLike apCommentLike : apCommentLikes) {
                        if (comment.getId().equals(apCommentLike.getCommentId())) {
                            apCommentVo.setOperation((short) 0);
                        }
                    }
                    list.add(apCommentVo);
                });
                return ResponseResult.okResult(list);
            } else {
                return ResponseResult.okResult(apComments);
            }
        }
    }
}
